package com.solomiao.demo.multi.thread.demo3;

import com.solomiao.demo.multi.thread.demo2.ThreadImplementDemo2;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @desc 线程的停止
 * */
public class MainDemo3 {

    public static int count = 0;

    public static int count1 = 0;

    // 使用 AtomicInteger 保证原子性
    public static AtomicInteger count2 = new AtomicInteger(0);

    public static int count3 = 0;

    private static final Object lock = new Object();
    private static int count4 = 0;

    public static void main(String[] args) throws InterruptedException {
        // 通过标志位停止线程
        // 通过实现Runnable接口创建线程
        ThreadImplementDemo3 threadImplementDemo = new ThreadImplementDemo3();
        Thread thread1 = new Thread(threadImplementDemo);
        Thread thread2 = new Thread(threadImplementDemo);
        // 启动线程
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("主线程：子线程已退出");
        System.out.println("主线程：count = " + count);
        System.out.println("主线程：count1 = " + count1);
        System.out.println("主线程：count2 = " + count2.get());
        System.out.println("主线程：count3 = " + count3);
        System.out.println("主线程：count4 = " + count4);
    }

    // 静态同步方法
    public static synchronized void incrementCounter() {
        count3 ++; // 操作的是静态变量
    }

    // 静态同步方法
    public static void incrementCounter4() {
        synchronized (lock) {
            count4 ++; // 操作的是静态变量
        }
    }

}
